package com.test.reggie.model.fragment.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.test.reggie.R;
import com.test.reggie.base.BaseFragment;
import com.test.reggie.base.BaseRVAdapter;
import com.test.reggie.base.BaseRVHolder;
import com.test.reggie.bean.AddShoppingCartBean;
import com.test.reggie.bean.CategoryListBean;
import com.test.reggie.bean.DishListBean;
import com.test.reggie.bean.FlavorModel;
import com.test.reggie.bean.ShoppingCartListBean;
import com.test.reggie.bean.State;
import com.test.reggie.bean.StringBean;
import com.test.reggie.bean.UserBean;
import com.test.reggie.databinding.FragmentHomeBinding;
import com.test.reggie.http.API;
import com.test.reggie.model.jiesuan.JiesuanActivity;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomePrensenter> implements
        HomeView, View.OnClickListener {

    private BaseRVAdapter<CategoryListBean.DataBean> adapterLeft;
    private BaseRVAdapter<DishListBean.DataBean> adapterRight;
    private int mpos = 0;
    private BasePopupView basePopupView;
    private UserBean userBean;
    private int pos;
    private BasePopupView cartPopupView;
    private int JIESUAN = 201;

    @Override
    protected HomePrensenter createPresenter() {
        return new HomePrensenter(this);
    }

    @Override
    protected void initView() {
        viewBinding.rlLookCart.setOnClickListener(this::onClick);
        viewBinding.btnJiesuan.setOnClickListener(this::onClick);
        mpos = 0;
        userBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.user)),
                UserBean.class);
    }

    @Override
    protected void initData() {
        //菜品分类
        YUtils.showLoading("加载中...");
        presenter.categoryList();//根据条件查询分类数据
        adapterLeft = new BaseRVAdapter<CategoryListBean.DataBean>(R.layout.item_category) {
            @Override
            public void onBindVH(BaseRVHolder holder, CategoryListBean.DataBean data, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);

                tv_name.setText("" + data.getName());
                if (position == mpos) {
                    tv_name.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                    tv_name.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                } else {
                    tv_name.setTextColor(getResources().getColor(R.color.colorBlack));
                    tv_name.setBackgroundColor(0);
                }

                tv_name.setOnClickListener(v -> {
                    mpos = holder.getAdapterPosition();
                    adapterLeft.notifyDataSetChanged();

                    //分类对应的列表
                    YUtils.showLoading("加载中...");
                    if (data.getType() == 1) {
                        presenter.dishList(data.getId());
                        adapterRight();
                    } else {
                        presenter.setmealList(data.getId());
                        adapterRight();
                    }
                });
            }
        };
        empty("暂无数据");
        viewBinding.rvLeft.setAdapter(adapterLeft);
        viewBinding.rvLeft.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
    }

    private void adapterRight() {
        adapterRight = new BaseRVAdapter<DishListBean.DataBean>(R.layout.item_categorylist) {
            @Override
            public void onBindVH(BaseRVHolder holder, DishListBean.DataBean data, int position) {
                TextView tv_name = holder.getView(R.id.tv_name);
                CircleImageView civ = holder.getView(R.id.civ);
                TextView tv_add = holder.getView(R.id.tv_add);

                Glide.with(getActivity()).load(API.kv.decodeString(State.ip) +
                        "/common/download?name=" + data.getImage())
                        .placeholder(R.drawable.icon_no_data).into(civ);

                tv_name.setText("" + data.getName());
                holder.setText(R.id.tv_description, data.getDescription());
                holder.setText(R.id.tv_price, "￥" + data.getPrice());

                tv_add.setOnClickListener(v -> {
                    pos = position;
                    if (data.getFlavors() != null && data.getFlavors().size() > 0) {
                        for (int i = 0; i < shoppingCartList.size(); i++) {
                            if (shoppingCartList.get(i).getName().equals(data.getName())) {
                                //添加购物车
                                YUtils.showLoading("添加中...");
                                Map<String, Object> mapAddShoppingCart = new HashMap<>();
                                mapAddShoppingCart.put("userId", userBean.getData().getId());//用户id
                                mapAddShoppingCart.put("amount", data.getPrice());//金额
                                if (data.getFlavors() != null && data.getFlavors().size() > 0) {
                                    mapAddShoppingCart.put("dishId", data.getId());//菜品id
                                } else {
                                    mapAddShoppingCart.put("setmealId", data.getId());//套餐id
                                }
                                mapAddShoppingCart.put("image", data.getImage());//图片
                                mapAddShoppingCart.put("name", data.getName());//名称
                                presenter.addShoppingCart(mapAddShoppingCart);//添加购物车
                                return;
                            }
                        }

                        //选择规格
                        basePopupView = new XPopup.Builder(getActivity())
                                .asCustom(new FlavorCommentPopup(getActivity(), data, position))
                                .show();
                    } else {
                        //添加购物车
                        YUtils.showLoading("添加中...");
                        Map<String, Object> mapAddShoppingCart = new HashMap<>();
                        mapAddShoppingCart.put("userId", userBean.getData().getId());//用户id
                        mapAddShoppingCart.put("amount", data.getPrice());//金额
                        if (data.getFlavors() != null && data.getFlavors().size() > 0) {
                            mapAddShoppingCart.put("dishId", data.getId());//菜品id
                        } else {
                            mapAddShoppingCart.put("setmealId", data.getId());//套餐id
                        }
                        mapAddShoppingCart.put("image", data.getImage());//图片
                        mapAddShoppingCart.put("name", data.getName());//名称
                        presenter.addShoppingCart(mapAddShoppingCart);//添加购物车
                    }
                });
            }
        };
        emptyRight("暂无数据");
        viewBinding.rvRight.setAdapter(adapterRight);
        viewBinding.rvRight.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == JIESUAN && resultCode == Activity.RESULT_OK) {
            presenter.shoppingCartList(userBean.getData().getId());//查看购物车
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_jiesuan://去结算
                Intent intent = new Intent(getActivity(), JiesuanActivity.class);
                startActivityForResult(intent, JIESUAN);
                break;
            case R.id.rl_look_cart://查看购物车
                cartPopupView = new XPopup.Builder(getActivity())
                        .asCustom(new CartPopup(getActivity()))
                        .show();
                break;
            default:
                break;
        }
    }

    public class CartPopup extends BottomPopupView {

        private BaseRVAdapter<ShoppingCartListBean.DataBean> carAdapter;
        private RecyclerView rv_cart;
        private TextView tv_clear;

        public CartPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.cart_bottom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            rv_cart = findViewById(R.id.rv_cart);
            tv_clear = findViewById(R.id.tv_clear);

            presenter.shoppingCartList(userBean.getData().getId());//查看购物车
            carAdapter = new BaseRVAdapter<ShoppingCartListBean.DataBean>(R.layout.item_cart) {
                @Override
                public void onBindVH(BaseRVHolder holder, ShoppingCartListBean.DataBean data, int position) {
                    TextView tv_name = holder.getView(R.id.tv_name);
                    CircleImageView civ = holder.getView(R.id.civ);
                    TextView tv_jian = holder.getView(R.id.tv_jian);
                    TextView tv_num = holder.getView(R.id.tv_num);
                    TextView tv_add = holder.getView(R.id.tv_add);

                    Glide.with(getActivity()).load(API.kv.decodeString(State.ip) +
                            "/common/download?name=" + data.getImage())
                            .placeholder(R.drawable.icon_no_data).into(civ);

                    tv_name.setText("" + data.getName());
                    holder.setText(R.id.tv_price, "￥" + data.getAmount());
                    tv_num.setText("" + data.getNumber());

                    tv_add.setOnClickListener(v -> {
                        pos = position;
                        //添加购物车
                        YUtils.showLoading("添加中...");
                        Map<String, Object> mapAddShoppingCart = new HashMap<>();
                        mapAddShoppingCart.put("userId", userBean.getData().getId());//用户id
                        mapAddShoppingCart.put("amount", data.getAmount());//金额
                        if (data.getDishId() != null) {
                            mapAddShoppingCart.put("dishId", data.getDishId());//菜品id
                        } else {
                            mapAddShoppingCart.put("setmealId", data.getSetmealId());//套餐id
                        }
                        mapAddShoppingCart.put("image", data.getImage());//图片
                        mapAddShoppingCart.put("name", data.getName());//名称
                        presenter.addShoppingCart(mapAddShoppingCart);//添加购物车

                        carAdapter.getData().get(pos).setNumber(data.getNumber() + 1);
                        carAdapter.notifyItemChanged(pos);
                    });

                    tv_jian.setOnClickListener(v -> {
                        pos = position;
                        //编辑购物车
                        YUtils.showLoading("移除中...");
                        Map<String, Object> mapAddShoppingCart = new HashMap<>();
                        mapAddShoppingCart.put("userId", userBean.getData().getId());//用户id
                        mapAddShoppingCart.put("amount", data.getAmount());//金额
                        if (data.getDishId() != null) {
                            mapAddShoppingCart.put("dishId", data.getDishId());//菜品id
                        } else {
                            mapAddShoppingCart.put("setmealId", data.getSetmealId());//套餐id
                        }
                        mapAddShoppingCart.put("image", data.getImage());//图片
                        mapAddShoppingCart.put("name", data.getName());//名称
                        presenter.updateShoppingCart(mapAddShoppingCart);//编辑购物车

                        if (data.getNumber() == 1) {
                            carAdapter.remove(pos);
                        } else {
                            carAdapter.getData().get(pos).setNumber(data.getNumber() - 1);
                            carAdapter.notifyItemChanged(pos);
                        }
                    });
                }
            };
            empty("暂无数据");
            rv_cart.setAdapter(carAdapter);
            rv_cart.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
            carAdapter.setNewData(shoppingCartList);

            tv_clear.setOnClickListener(v -> {
                //清空购物车
                presenter.cleanShoppingCart(userBean.getData().getId());
            });
        }

        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        private void empty(String msg) {
            View empty = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_data, null, false);
            TextView tv_tip = empty.findViewById(R.id.tv_tip);
            tv_tip.setText(msg);
            carAdapter.setEmptyView(empty);
        }
    }

    public class FlavorCommentPopup extends CenterPopupView {

        private DishListBean.DataBean data;
        private TextView tv_name, tv_price, tv_add_cart;
        private RecyclerView rv_flavor;
        private BaseRVAdapter<DishListBean.DataBean.FlavorsBean> adapterFlavor;
        private int mposFlavor = 0;
        private FlavorModel flavorModel;
        private List<String> name = new ArrayList<>();
        private StringBuffer names;
        private int position;

        public FlavorCommentPopup(@NonNull Context context, DishListBean.DataBean data, int position) {
            super(context);
            this.data = data;
            this.position = position;
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.custom_bottom_popup_flavor;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            tv_name = findViewById(R.id.tv_name);
            tv_price = findViewById(R.id.tv_price);
            tv_add_cart = findViewById(R.id.tv_add_cart);
            rv_flavor = findViewById(R.id.rv_flavor);

            tv_name.setText(data.getName());
            tv_price.setText("￥" + data.getPrice());
            adapterFlavor = new BaseRVAdapter<DishListBean.DataBean.FlavorsBean>(R.layout.item_flavor) {
                @Override
                public void onBindVH(BaseRVHolder holder, DishListBean.DataBean.FlavorsBean data, int position) {
                    RecyclerView rv_flavor_value = holder.getView(R.id.rv_flavor_value);
                    holder.setText(R.id.tv_flavor_name, data.getName());

                    List<String> list = new Gson().fromJson(data.getValue(), (new TypeToken<List<String>>() {
                    }).getType());

                    List<FlavorModel> flavorModels = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        flavorModel = new FlavorModel();
                        flavorModel.setMposFlavor(i);
                        flavorModel.setName(list.get(i));
                        flavorModels.add(flavorModel);
                    }

                    BaseRVAdapter<FlavorModel> stringBaseRVAdapter = new BaseRVAdapter<FlavorModel>(R.layout.item_flavor_name) {
                        @Override
                        public void onBindVH(BaseRVHolder holder, FlavorModel data, int position) {
                            TextView tv_name = holder.getView(R.id.tv_name);

                            tv_name.setText(data.getName());

                            tv_name.setOnClickListener(v -> {
                                mposFlavor = holder.getAdapterPosition();
                                notifyDataSetChanged();
                            });

                            if (mposFlavor == position) {
                                tv_name.setBackground(getResources().getDrawable(R.drawable.shape_tv_bg_yello));
                                name.add(data.getName());
                            } else {
                                tv_name.setBackground(getResources().getDrawable(R.drawable.shape_tv_boder_yello));
                                if (name.contains(data.getName())) {
                                    name.remove(data.getName());
                                }
                            }
                        }
                    };
                    rv_flavor_value.setAdapter(stringBaseRVAdapter);
                    rv_flavor_value.setLayoutManager(new GridLayoutManager(getActivity(), 4));//列数设置
                    stringBaseRVAdapter.setNewData(flavorModels);
                }
            };
            rv_flavor.setAdapter(adapterFlavor);
            rv_flavor.setLayoutManager(new GridLayoutManager(getActivity(), 1));//列数设置
            adapterFlavor.setNewData(data.getFlavors());

            tv_add_cart.setOnClickListener(v -> {
                pos = position;

                //添加购物车
                names = new StringBuffer();
                for (int i = 0; i < name.size(); i++) {
                    names.append(name.get(i) + ",");
                }
                String dishFlavor = names.substring(0, names.length() - 1);

                YUtils.showLoading("添加中...");
                Map<String, Object> mapAddShoppingCart = new HashMap<>();
                mapAddShoppingCart.put("userId", userBean.getData().getId());//用户id
                mapAddShoppingCart.put("amount", data.getPrice());//金额
                mapAddShoppingCart.put("dishFlavor", dishFlavor);//口味
                mapAddShoppingCart.put("dishId", data.getId());//菜品id
                mapAddShoppingCart.put("image", data.getImage());//图片
                mapAddShoppingCart.put("name", data.getName());//名称
                presenter.addShoppingCart(mapAddShoppingCart);//添加购物车
            });
        }

        // 设置最大宽度，看需要而定，
        @Override
        protected int getMaxWidth() {
            return super.getMaxWidth();
        }

        // 设置最大高度，看需要而定
        @Override
        protected int getMaxHeight() {
            return super.getMaxHeight();
        }

        // 设置自定义动画器，看需要而定
        @Override
        protected PopupAnimator getPopupAnimator() {
            return super.getPopupAnimator();
        }

        /**
         * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
         *
         * @return
         */
        protected int getPopupWidth() {
            return 0;
        }

        /**
         * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
         *
         * @return
         */
        protected int getPopupHeight() {
            return 0;
        }
    }

    private void empty(String msg) {
        View empty = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_data, null, false);
        TextView tv_tip = empty.findViewById(R.id.tv_tip);
        tv_tip.setText(msg);
        adapterLeft.setEmptyView(empty);
    }

    private void emptyRight(String msg) {
        View empty = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_data, null, false);
        TextView tv_tip = empty.findViewById(R.id.tv_tip);
        tv_tip.setText(msg);
        adapterRight.setEmptyView(empty);
    }

    @Override
    public void categoryListSuccess(CategoryListBean bean) {
        if (bean.getCode() == 200) {
            adapterLeft.setNewData(bean.getData());

            presenter.shoppingCartList(userBean.getData().getId());//查看购物车

            if (bean.getData().size() > 0) {
                int type = bean.getData().get(0).getType();
                if (type == 1) {
                    presenter.dishList(bean.getData().get(0).getId());
                    adapterRight();
                } else {
                    presenter.setmealList(bean.getData().get(0).getId());
                    adapterRight();
                }
            }
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void dishListSuccess(DishListBean bean) {
        YUtils.hideLoading();
        if (bean.getCode() == 200) {
            adapterRight.setNewData(bean.getData());
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void addShoppingCartSuccess(AddShoppingCartBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            if (basePopupView != null && basePopupView.isShow()) {
                basePopupView.dismiss();
            }

            presenter.shoppingCartList(userBean.getData().getId());//查看购物车
        }
    }

    private List<ShoppingCartListBean.DataBean> shoppingCartList;

    @Override
    public void shoppingCartListSuccess(ShoppingCartListBean bean) {
        if (bean.getCode() == 200) {
            shoppingCartList = bean.getData();

            BigDecimal zongjia = new BigDecimal(0);
            BigDecimal znum = new BigDecimal(0);
            if (shoppingCartList.size() > 0) {
                viewBinding.iv.setImageResource(R.drawable.icon_waimai);
                viewBinding.rlLookCart.setEnabled(true);
                viewBinding.btnJiesuan.setEnabled(true);
                viewBinding.btnJiesuan.setBackground(getResources().getDrawable(R.drawable.shape_ll_bg_yello));

                for (int i = 0; i < shoppingCartList.size(); i++) {
                    BigDecimal num = new BigDecimal(shoppingCartList.get(i).getNumber());
                    BigDecimal amount = shoppingCartList.get(i).getAmount();
                    BigDecimal jiage = num.multiply(amount);
                    zongjia = zongjia.add(jiage);
                    znum = znum.add(num);
                }
                viewBinding.tvZongjia.setText("￥" + zongjia);
                viewBinding.tvNum.setVisibility(View.VISIBLE);
                if (Integer.parseInt(String.valueOf(znum)) > 99) {
                    viewBinding.tvNum.setText("99+");
                } else {
                    viewBinding.tvNum.setText("" + znum);
                }
            } else {
                viewBinding.iv.setImageResource(R.drawable.icon_waimai_no);
                viewBinding.rlLookCart.setEnabled(false);
                viewBinding.btnJiesuan.setEnabled(false);
                viewBinding.btnJiesuan.setBackground(getResources().getDrawable(R.drawable.shape_ll_bg_gray));
                viewBinding.tvNum.setVisibility(View.GONE);
                zongjia = new BigDecimal(0);
                viewBinding.tvZongjia.setText("￥" + zongjia);
                if (cartPopupView != null && cartPopupView.isShow()) {
                    cartPopupView.dismiss();
                }
            }
        }
    }

    @Override
    public void cleanShoppingCartSuccess(StringBean bean) {
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            presenter.shoppingCartList(userBean.getData().getId());//查看购物车
            cartPopupView.dismiss();
        }
    }
}